import json
import serverFiles


_demo = {
        "@N":"do_u1_pv_out",
        "@UNIT":"",#单位
        "@D":"输出",#描述
        "@DN":"mbs",
        "@AD":"D216.421606",
        "@DT":"9",
        "@VT":"1",
        "@ODT":"9",
        "@PCS":"3",#小数
        "ACV":
        {
            "@AM":"0",
            "@AR":"0",
            "@AI":"1",
            "@ATP":"360"
        },
        "ALM":
        {
            "@E":"1",
            "@HHL":"",
            "@HL":"",
            "@LL":"",
            "@LLL":""
        },
        "WP":
        {
            "@EW":"1",
            "@EWP":"1",
            "@WMAV":"",
            "@WMIV":"",
            "@ELP":"1"
        },
        "CVT":
        {
            "@ELC":"0",
            "@CT":"0",
            "@PMAV":"0",
            "@PMIV":"0",
            "@OMAV":"0",
            "@OMIV":"0"
        },
        "@AUTH":[
            {
                "@EL":0,
                "@OKI":
                {
                    "@Comment":"",
                    "@N":"",
                    "@OT":2,
                    "@T":41
                },
                "@PM":0,
                "@ST":1
            }
        ],
        "@IV":"0",
        "@LV":"",
        "@IVEVT":"1"
    }

#转换variable
# 变量文件格式转换
def traverse_vs_dict(data, parent_name='', res={}):
    if isinstance(data, dict):
        if '@N' in data and data['@N'] != '':
            parent_name += data['@N'] + '/'
        for k, v in data.items():
            if k == 'VS':
                for item in v:
                    if isinstance(item, dict):
                        if '@N' in item:
                            vs_name = parent_name + item['@N']
                            res[vs_name] = item
                            if 'GS' in res[vs_name]:
                                res[vs_name].pop("GS")
            else:
                traverse_vs_dict(v, parent_name, res)
    elif isinstance(data, list):
        for item in data:
            traverse_vs_dict(item, parent_name, res)
    return res

json_data = traverse_vs_dict(serverFiles.variable)

def getVar(varName,default = None):
    varName = varName.replace('.','/')
    return json_data.get(varName,default)

# 在variableUtils.py中添加
_ext_dict_processed = {}  # 用于跟踪哪些变量已经处理过

def syncExtDict(varName, ext_dict):
    """
    将扩展属性同步到json_data中
    
    参数:
    varName - 变量名
    ext_dict - 扩展属性字典
    """
    global json_data, _ext_dict_processed
    
    # 防止重复处理
    key = f"{varName}_{hash(str(ext_dict))}"
    if key in _ext_dict_processed:
        return
    
    # 标记为已处理
    _ext_dict_processed[key] = True
    
    # 从json_data中获取变量
    varName = varName.replace('.', '/')
    underline_varName = varName.replace('/', '_')  #寻找变量时,会用"_"访问
    var_data = json_data.get(varName)
    
    if var_data is None:
        return
        
    # 处理扩展属性覆盖
    if ext_dict:
        # 处理精度
        if 'pcs' in ext_dict and ext_dict['pcs'] is not None:
            var_data['@PCS'] = str(ext_dict['pcs'])
            
        # 处理单位
        if 'unit' in ext_dict:
            var_data['@UNIT'] = ext_dict['unit']
            
        # 处理上下限
        if 'wmav' in ext_dict and 'WP' in var_data:
            var_data['WP']['@WMAV'] = str(ext_dict['wmav'])
            
        if 'wmiv' in ext_dict and 'WP' in var_data:
            var_data['WP']['@WMIV'] = str(ext_dict['wmiv'])
    
    json_data[underline_varName] = var_data


def getUnit(varName,default = None):
    v = getVar(varName)
    if v != None:
        return v.get('@UNIT',default)
    return default 

def getPCS(varName,default = None):
    v = getVar(varName)
    if v != None:
        DT = int(v.get('@DT',0))
        if DT == 9 or DT == 10:
            _ = v.get('@PCS',None)
            if _ != None and str(_).isnumeric():
                return int(_)
    return default 

def hasVar(varName):
    if isinstance(varName,str):
        varName = varName.replace('.','/')
        return varName in json_data
    return False


def getMax(varName, default=None):
    try:
        v = getVar(varName)
        if v is not None:
            wp = v.get('WP')
            if wp is not None and wp != '':
                value = wp.get('@WMAV', default)
                return float(value)
        return default
    except Exception as e:
        # 捕捉任何意外的异常
        print(f"Error: An unexpected error occurred for {varName}: {e}")
        return default



def getMin(varName, default=None):
    try:
        v = getVar(varName)
        if v is not None:
            wp = v.get('WP')
            if wp is not None and wp != '':
                value = wp.get('@WMIV', default)
                return float(value)
        return default
    except Exception as e:
        # 捕捉任何意外的异常
        print(f"Error: An unexpected error occurred for {varName}: {e}")
        return default



if __name__ == '__main__':
    # 调用
    json_data = serverFiles.variable
    
    result_dict = {}
    # parse_json(json_data, "", result_dict)
    result_dict = traverse_vs_dict(json_data)
    # print(result_dict.keys())

    # with open('test.json', 'w') as f:
    #     json.dump(result_dict, f)
    
    with open('data.json', 'w', encoding='utf-8') as f:
        json.dump(result_dict, f, ensure_ascii=False)



